//
//  RequestHelper.m
//  NMC_iOS
//
//  Created by Nong Nghia on 7/30/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "RequestHelper.h"
#import "JSON.h"
#import "AFNetworking.h"
#import "CMCOperationQueue.h"
#import "CMCHTTPClient.h"

@implementation RequestHelper

+ (void)requestJSONWithURL:(NSURL*)_URL
                 andParams:(NSDictionary*)_params
                   success:(void (^)(id result))success
                   failure:(void (^)(NSError *error))failure
{
    NSMutableURLRequest *urlRequest=[[[NSMutableURLRequest alloc] initWithURL:_URL] autorelease];
    [urlRequest setHTTPMethod:@"GET"];
    [urlRequest setTimeoutInterval:30.0];
    if (_params!=nil) {
        NSData * jSonData = [[_params JSONFragment] dataUsingEncoding:NSUTF8StringEncoding];
        
        [urlRequest addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
        [urlRequest addValue:[NSString stringWithFormat:@"%d",jSonData.length] forHTTPHeaderField:@"Content-Length"];
        
        [urlRequest setHTTPBody:jSonData];
        
    }

    AFHTTPRequestOperation *rOperation=[[[AFHTTPRequestOperation alloc] initWithRequest:urlRequest] autorelease];
    
    [rOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        if (responseObject!=nil) {
            if (success) {
                success(responseObject);
            }
        }
        else{
            if (failure) {
                failure([NSError errorWithDomain:@"CMCSoftware" code:500 userInfo:[NSDictionary dictionaryWithObject:@"response null" forKey:NSLocalizedDescriptionKey]]);
            }
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        if (failure) {
            failure(error);
        }
        
    }];
    
    [[CMCOperationQueue sharedInstance] addOperation:rOperation];
    
}

+ (void)requestImageWithURL:(NSURL*)_URL
                    success:(void (^)(id result))success
                    failure:(void (^)(NSError *error))failure{
    
    NSMutableURLRequest *urlRequest=[[[NSMutableURLRequest alloc] initWithURL:_URL] autorelease];
    [urlRequest setHTTPMethod:@"POST"];
    [urlRequest setTimeoutInterval:30.0];

    AFImageRequestOperation *irOperation =[AFImageRequestOperation imageRequestOperationWithRequest:urlRequest imageProcessingBlock:^UIImage *(UIImage *image) {
        return image;
    } success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) {
        if (success) {
            success(image);
        }
    } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) {
        if (failure) {
            failure(error);
        }
    }];
    
    [[NSOperationQueue currentQueue] addOperation:irOperation];
    
}



@end
